using System.Linq;
using System.Reflection;
using Castle.ActiveRecord;
using Cooking.Core.DataInterfaces;

namespace Cooking.Data
{
    public class DaoBase<T> : IDao<T> where T : class
    {
        public T LoadById(int id)
        {
            return ActiveRecordMediator.FindByPrimaryKey(typeof (T), id) as T;
        }

        public void Save(T item)
        {
            ActiveRecordMediator.Save(item);
        }

        public int Create(T item)
        {
            ActiveRecordMediator.Create(item);
            return PrimaryKeyValue(item);
        }

        private int PrimaryKeyValue(T item)
        {
            PropertyInfo key = FindPrimaryKey(item);
            return (int)key.GetValue(item, null);
        }

        private PropertyInfo FindPrimaryKey(T item)
        {
            return (from pi in typeof (T).GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
                     where pi.GetCustomAttributes(typeof (Castle.ActiveRecord.PrimaryKeyAttribute), true) != null
                     select pi).First();

        }
        
    }
}